package crp.core.workflow.domain.services;

import com.qwlabs.security.Caller;
import com.qwlabs.cdi.Primary;
import crp.core.workflow.domain.models.WorkflowCandidate;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Primary
@ApplicationScoped
public class WorkflowCandidateLoaderCombiner implements WorkflowCandidateLoader {
    private final Instance<WorkflowCandidateLoader> loaders;

    @Inject
    public WorkflowCandidateLoaderCombiner(Instance<WorkflowCandidateLoader> loaders) {
        this.loaders = loaders;
    }

    @Override
    public Set<WorkflowCandidate> load(@NotNull Caller caller) {
        return loaders.stream()
                .map(loader -> loader.load(caller))
                .filter(Objects::nonNull)
                .flatMap(Set::stream)
                .collect(Collectors.toSet());
    }
}
